<template>
	<view class="container position-relative">
		<view style="margin-bottom: 130rpx">
			<view class="section-1" @click.stop="chooseAddress">
				<view v-if="!userState.address.id" class="choose-address">
					<view>请选择地址</view>
					<uni-icons type="right" color="grey" size="25" />
				</view>
				<template v-else="userState.address.id">
					<list-cell>
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center justify-content-between mb-10">
								<view class="font-size-extra-lg text-color-base">{{ userState.address.address }}</view>
								<uni-icons type="right" size="20" color="grey" />
							</view>
							<view class="d-flex text-color-assist font-size-sm align-items-center">
								<view class="mr-10">{{ userState.address.name }}</view>
								<view class="mr-10">{{ userState.address.sex == 1 ? '先生' : '女士' }}</view>
								<view>电话:{{ userState.address.phone }}</view>
							</view>
						</view>
					</list-cell>
				</template>
			</view>
			<!-- 购物车列表 begin -->
			<view class="section-2">
				<view class="cart d-flex flex-column">
					<list-cell last v-for="(item, index) in cart" :key="index">
						<view class="w-100 d-flex flex-column">
							<view class="d-flex align-items-center mb-10">
								<view class="name-and-props overflow-hidden">
									<view class="text-color-base font-size-lg">
										{{ item.title }}
									</view>
								</view>
								<view class="d-flex flex-fill justify-content-between align-items-center text-color-base font-size-lg">
									<view>x{{ item.number }}</view>
									<view>￥{{ item.price }}</view>
								</view>
							</view>
							<view class="text-truncate font-size-base text-color-assist">
								{{ item.props_text }}
							</view>
						</view>
					</list-cell>
				</view>
				<list-cell last>
					<view class="flex-fill d-flex justify-content-end align-items-center">
						<view>总计￥{{ total }},实付</view>
						<view class="font-size-extra-lg font-weight-bold">￥{{ amount }}</view>
					</view>
				</list-cell>
			</view>
			<!-- 购物车列表 end -->
			<view class="d-flex align-items-center justify-content-start font-size-sm text-color-warning" style="padding: 20rpx 0">
				<view class="iconfont iconhelp line-height-100"></view>
				<view>优惠券不与满赠、满减活动共享</view>
			</view>
			<!-- 支付方式 begin -->
			<view class="payment">
				<list-cell last :hover="false">
					<text>支付方式</text>
				</list-cell>
				<list-cell last>
					<view class="d-flex align-items-center justify-content-between w-100">
						<view class="iconfont iconwxpay line-height-100 payment-icon" style="color: #7eb73a"></view>
						<view class="flex-fill">微信支付</view>
						<view class="iconfont iconradio-button-on line-height-100 checkbox checked"></view>
					</view>
				</list-cell>
			</view>
			<!-- 支付方式 end -->
			<!-- 备注 begin -->
			<list-cell arrow last @click="goToRemark">
				<view class="d-flex flex-fill align-items-center justify-content-between overflow-hidden">
					<view class="flex-shrink-0 mr-20">备注</view>
					<view class="text-color-primary flex-fill text-truncate text-right">{{ remark || '点击填写备注' }}</view>
				</view>
			</list-cell>
			<!-- 备注 end -->
		</view>
		<!-- 付款栏 begin -->
		<view class="w-100 pay-box position-fixed fixed-bottom d-flex align-items-center justify-content-between bg-white">
			<view class="font-size-sm" style="margin-left: 20rpx">合计：</view>
			<view class="font-size-lg flex-fill">￥{{ amount }}</view>
			<view class="bg-primary h-100 d-flex align-items-center just-content-center text-color-white font-size-base" style="padding: 0 60rpx" @tap="submit">付款</view>
		</view>
		<!-- 付款栏 end -->
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="msgType" :message="messageText" :duration="3500" />
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import listCell from '../components/list-cell/list-cell';
import { onLoad } from '@dcloudio/uni-app';
import { getCart, setEmptyCart } from '../../store/shop';
import { state as userState, setAddUserOrder, setSuccessOrder } from '../../store/user';
import getOrders, { Order, OrderGoods, WxJsOrder } from '../../vendor/order_food/order';
import { ReqWxJsOrder } from '../../vendor/order_food/order';
import http from '../../vendor/http';

type ReqPayment = {
	Code: number;
	order: Order;
};

const { wxCreateOrder } = getOrders();

const cart = getCart();
const remark = ref('');
let reqStatusInter = null;
const msgType = ref('warn');
const messageText = ref('');
const message = ref();

// let  adjustPrices:any = null  // 调整的价格
// let adjustStocks:any = null   // 调整的库存

onLoad(({ r }) => {
	remark.value = r ? r : '';

	console.log(cart)
});

const total = computed(() => {
	return ( cart.reduce((acc, cur) => acc + cur.number * cur.price, 0) ).toFixed(2);
});
const amount = computed(() => {

	return (cart.reduce((acc, cur) => acc + cur.number * cur.price, 0) ).toFixed(2);
});

function goToRemark() {
	const url = remark.value ? '/pages/user/remark?r=' + remark.value : '/pages/user/remark';
	uni.navigateTo({
		url: url
	});
}
function chooseAddress() {
	uni.navigateTo({
		url: '/pages/user/address'
	});
}

 

function submit() {
	if (!userState.address || !userState.address.id) {
		uni.showToast({
			title: '请先选择收货地址~',
			icon: 'none'
		});
		return;
	}
	
	uni.showLoading()

	//  #ifdef  MP-WEIXIN
	const orderGoods: Array<OrderGoods> = [];
	// jsapi 生单
	let priceAll = 0;
	cart.forEach((item) => {
		priceAll += item.price;
		orderGoods.push({
			id: item.id,
			count: item.number,
			price: parseInt((item.price * 100).toFixed(2)) // 传入的单位是分
		});
	});

	if (!priceAll) {
		uni.showToast({
			title: '订单金额为空,请确认~',
			icon: 'none'
		});
	}

	// 轮询判断订单是否支付成功

	const reqWx: ReqWxJsOrder = {
		order_goods: JSON.stringify(orderGoods),
		des: remark.value,
		address: userState.address.address,
		location: userState.address.location,
		longitude: userState.address.longitude,
		latitude: userState.address.latitude,
		phone: userState.address.phone,
		host_name: userState.address.name
	};

	wxCreateOrder(reqWx, (res: WxJsOrder) => {
		//判断是否做了商品库存或者价格的调整
		
		if (res.prices && res.stocks ) {
			
			const prices = JSON.parse(res.prices); // id=>price
			let ids = Object.keys(prices);
			ids.forEach((id: any) => {
				const e = cart.find((item) => item.id == id);
				e.price = parseFloat((prices[id] / 100).toFixed(2));
			});

			const stocks = JSON.parse(res.stocks); // id=>price
			ids = Object.keys(stocks);
			ids.forEach((id: any) => {
				const i = cart.findIndex((item) => item.id == id);
				cart[i].number = stocks[id];

				if (cart[i].number == 0) {
					cart.splice(i, 1);
				}
			});

			messageText.value = '部分商品调整了价格及缺货,请核对后支付~';
			message.value.open();
			
			return;
		}
		if (res.prices) {
			// 调了价格
			const prices = JSON.parse(res.prices); // id=>price
			let ids = Object.keys(prices);
			ids.forEach((id: any) => {
				const i = cart.findIndex((item) => item.id == id);
				cart[i].price = parseFloat((prices[id] / 100).toFixed(2));

				if (cart[i].price <= 0) {
					cart.splice(i, 1);
				}
			});

			messageText.value = '部分商品调整了价格,请核对后支付~';
			message.value.open();
			return;
		} else if (res.stocks) {
			// 调了库存
			const stocks = JSON.parse(res.stocks); // id=>price
			const ids = Object.keys(stocks);
			ids.forEach((id: any) => {
				const index = cart.findIndex((item) => item.id == id);
				if (stocks[id] <= 0) {
					cart.splice(index, 1);
				} else {
					cart[index].number = stocks[id];
				}
			});

			messageText.value = '部分商品缺货,请核对后下单~';
			message.value.open();
			return;
		}

		//  成功获取支付请求参数
		const func = () => {
			// 轮询验证订单状态

			reqStatusInter = setTimeout(() => {
				http.fetchGet(`order_status/${res.trade_no}`).then((res: ReqPayment) => {
					switch (res.order.status) {
						case 1:
							reqStatusInter && func();
							break;
						case 2:
							// 成功

							paySuccess(res.order);

							break;
						case 3:
							// 关闭
							toasting('支付失败', 'fail');
							clearTimeout(reqStatusInter);
							reqStatusInter = null;
							break;
					}
				});
			}, 1500);
		};
		func();

		// 付款
		uni.hideLoading()
		uni.requestPayment({
			provider: 'wxpay',
			orderInfo: 'orderInfo', //微信、支付宝订单数据 【注意微信的订单信息，键值应该全部是小写，不能采用驼峰命名】
			timeStamp: res.timestamp,
			nonceStr: res.nonce_str,
			package: res.package,
			signType: res.sign_type,
			paySign: res.pay_sign,
			fail: (res) => {
				// 用户取消支付  订单无效取消轮询访问
				console.log('客户取消支付');
			},
			complete: () => {
				// clearTimeout(reqStatusInter);
				// reqStatusInter = null;
			}
		});
	});

	// #endif

	// 测试
	// paySuccess()
}

const toasting = (title: string, icon: any = 'none') => {
	uni.showToast({
		title,
		icon
	});
};

// 付款成功后的处理函数
const paySuccess = (order) => {
	clearTimeout(reqStatusInter);
	reqStatusInter = null;
	toasting('支付成功', 'success');
	// 支付成功删除购物车信息
	setEmptyCart();

	//  加入全局订单信息
	setAddUserOrder(order);

	// 加入支付成功订单
	setSuccessOrder(order);

	// 跳转成功页
	uni.redirectTo ({
		url: '/pages/user/pay_success'
	});
};
</script>

<style lang="scss" scoped>
.container {
	padding: 30rpx;
	overflow-y: scroll;
}

.arrow {
	width: 50rpx;
	height: 50rpx;
	position: relative;
	margin-right: -10rpx;
}

.location {
	.store-name {
		font-size: $font-size-lg;
	}

	.iconfont {
		font-size: 50rpx;
		line-height: 100%;
		color: $color-primary;
	}
}

.section-1 {
	margin-bottom: 30rpx;
	.contact {
		.contact-tip {
			margin-left: 10rpx;
			border: 2rpx solid $color-primary;
			padding: 6rpx 10rpx;
			color: $color-primary;
		}
	}
}

.section-2 {
	.name-and-props {
		width: 65%;
	}
}

.payment {
	margin-bottom: 30rpx;

	.disabled {
		color: $text-color-grey;
	}

	.payment-icon {
		font-size: 44rpx;
		margin-right: 10rpx;
	}

	.checkbox {
		font-size: 36rpx;
		margin-left: 10rpx;
	}

	.checked {
		color: $color-primary;
	}
}

.pay-box {
	box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
	height: 150rpx;
}

.modal-content {
	.change-address-btn {
		line-height: 2;
		padding: 0 1em;
	}
	.pay_btn {
		width: 100%;
		border-radius: 50rem !important;
		line-height: 3;
	}
}
.choose-address {
	line-height: 50px;
	padding: 0 12px;
	background: white;
	display: flex;
	justify-content: space-between;
}
</style>
